package com.whz.gateway.handler.captcha.sms;

import cn.hutool.core.lang.Pair;
import com.whz.gateway.common.constants.GatewayConstant;
import com.whz.gateway.common.util.RegexUtils;
import com.whz.gateway.handler.AbstractGatewayHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author whz
 */
@Slf4j
@Component
public class SmsCheckHandler extends AbstractGatewayHandler {

    @Override
    protected Pair<Boolean, String> handler(ServerRequest request) {
        return check(request);
    }

    private static Pair<Boolean, String> check(ServerRequest request) {

        Optional<String> phone = request.queryParam(GatewayConstant.SMS_PARAM_PHONE);
        Optional<String> code = request.queryParam(GatewayConstant.SMS_PARAM_CODE);
        if (!phone.isPresent() || !StringUtils.hasText(phone.get())) {
            return new Pair<>(false, "电话号码不能为空");
        }
        if (!code.isPresent() || !StringUtils.hasText(code.get())) {
            return new Pair<>(false, "验证码不能为空");
        }
        if (!Pattern.matches(RegexUtils.PHONE_REG, phone.get())) {
            return new Pair<>(false, "电话号码格式不正确");
        }
        // todo 验证短信验证码
        return new Pair<>(false, "无效");
    }
}